package com.xo.file.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.xo.file.config.ConfigurationProperties.CosConfigurationProperties;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
@Schema(description = "腾讯云COS客户端配置")
@Tag(name = "腾讯云COS客户端配置")
public class CosClientConfig {

    @Resource
    private CosConfigurationProperties cosConfigurationProperties;

    private COSClient cosClient;

    @Bean
    public COSClient getCosClient() {
        //1.初始化凭证
        COSCredentials cred = new BasicCOSCredentials(cosConfigurationProperties.getSecretId(), cosConfigurationProperties.getSecretKey());

        //2.设置 bucket 的地域
        Region region = new Region(cosConfigurationProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        //3.生成 cos 客户端
        cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    @PreDestroy
    public void shutdownCosClient(){
        if (!Objects.isNull(cosClient)) {
            cosClient.shutdown();
        }
    }

}
